#!/usr/bin/python
#
# Copyright 2008 Qumranet, Inc. All rights reserved.
# Use is subject to license terms.
#

import os, sys, getopt
import subprocess
import traceback
from config import config
config.read('@CONFDIR@/vdsm.conf')

VDS_CLIENT = '@BINDIR@/vdsClient'
QEMU_IMG = config.get('vars', 'qemuimg')
SSL = config.getboolean('vars', 'ssl')

def ImageVerifier(img):
    if not img:
        img = os.environ.get('hda')

    if not img:
        rc = 0 
    else:
        p = subprocess.Popen([QEMU_IMG, "check", img], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        p.wait()
        rc = p.returncode
        sys.stdout.write(p.stdout.read(1024)+p.stderr.read(1024))
        if rc:
            uuid = os.path.splitext(os.path.basename(img))[0]
            ssl = [[], ['-s']][SSL]
            subprocess.Popen([VDS_CLIENT] + ssl + ['0', 'setImageLegality', uuid, 'ILLEGAL'])
            sys.stderr.write("Image corrupted\n")
    return rc

def main():
    """ Usage: img_verifier
        [-i image] - image to verify
    """
    try:
        img = ''
        opts, args = getopt.getopt(sys.argv[1:], "i:")
        for o,v in opts:
            if o == "-i":
                img = v
    except:
        print main.__doc__
        return 0

    try:
        # if 'recover', mean vdsmd service restarted.
        recover = os.environ.has_key('recover')
        # if 'migDest', mean we are in migration process.
        migDest = os.environ.has_key('migrationDest')
        migSrc = False
        exitMessage = os.environ.get('exitMessage')
        exitCode = os.environ.get('exitCode')
        if exitMessage and exitCode:
            if exitMessage=='Migration succeeded' and exitCode=='0':
                migSrc = True
        # do not run script if: vdsmd restarted or VM migrated
        if not recover and not migDest and not migSrc:
            ret = ImageVerifier(img)
        else:
            print "**** Skipping image validation script"
            return 0
    except:
        print traceback.format_exc()
        ret = -1

    if ret:
        print '**** Image Validation: FAIL'
    else:
        print '**** Image Validation: OK'
    return ret

if __name__ == "__main__":
    sys.exit(main())

